package com.ahs.validate;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Arrays;
import java.util.Objects;

/**
 * 枚举值校验,需要指定枚举字段所有可能的值,若值不指定或参数值为null,则不进行校验
 *
 * @author Song Lea
 */
public class AllowValueValidator implements ConstraintValidator<AllowValue, Object> {

    private int[] allowIntegerValues;
    private String[] allowStringValues;

    @Override
    public void initialize(AllowValue allowValue) {
        this.allowIntegerValues = allowValue.allowIntegerValues();
        this.allowStringValues = allowValue.allowStringValues();
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        if (value == null) {
            // 这里不校验null,一般字段上再指定@NotNull校验
            return true;
        }
        // 只针对String与Integer类型的枚举校验
        if (value instanceof String) {
            if (allowStringValues == null || allowStringValues.length == 0) {
                return true;
            }
            return Arrays.stream(allowStringValues).anyMatch(t -> Objects.equals(t, value.toString()));
        }
        if (value instanceof Integer) {
            if (allowIntegerValues == null || allowIntegerValues.length == 0) {
                return true;
            }
            return Arrays.stream(allowIntegerValues).anyMatch(t -> Objects.equals(t, value));
        }

        return true;
    }
}
